package com.smasher.decoration.group

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.smasher.decoration.DensityUtil
import com.smasher.decoration.R

/**
 * 配合GroupAdapter使用
 */
class GroupSwordDecoration(private val context: Context) : ItemDecoration() {

    private val dividerHeightInPx = 1

    private val backgroundPaint = Paint()
    private val textPaint = Paint()

    private var groupHeaderHeight = 0
    private var textSize = 24f

    private var textPaddingLeftCalculate = 0

    init {
        groupHeaderHeight = DensityUtil.dip2px(context, 26f)
        textPaddingLeftCalculate = DensityUtil.dip2px(context, 16f)
        textSize = DensityUtil.sp2px(context, 12f)

        // 头部背景画笔
        backgroundPaint.color = ContextCompat.getColor(context, R.color.color_head_background)

        // 头部文字画笔
        textPaint.textSize = textSize
        textPaint.color = ContextCompat.getColor(context, R.color.color_head_text)
    }

    fun setGroupHeaderHeight(height: Int) {
        groupHeaderHeight = DensityUtil.dip2px(context, height.toFloat())
    }

    fun setGroupHeaderTextSize(size: Int) {
        textSize = DensityUtil.sp2px(context, size.toFloat())
        textPaint.textSize = textSize
    }

    fun setGroupHeaderTextColor(@ColorInt id: Int) {
        textPaint.color = id
    }

    override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {

        val adapter = parent.adapter
        if (adapter is GroupSwordDelegate) {
            // 获取当前屏幕可见的 Item 数量
            val childCount = parent.childCount
            // 确定 canvas 的左右边界，刨除 padding
            val left = parent.paddingLeft
            val right = parent.width - parent.paddingRight
            for (i in 0 until childCount) {
                val child = parent.getChildAt(i)
                val position = parent.getChildLayoutPosition(child)
                if (adapter.isGroupHeader(position)) {
                    canvas.drawRect(
                        left.toFloat(),
                        (child.top - groupHeaderHeight).toFloat(),
                        right.toFloat(),
                        child.top.toFloat(),
                        backgroundPaint
                    )
                    val groupName: String = adapter.getGroupName(position)
                    val textPaddingLeft = textPaddingLeftCalculate
                    canvas.drawText(
                        groupName,
                        (left + textPaddingLeft).toFloat(),
                        getTextBaselineY(textPaint, child.top, groupHeaderHeight),
                        textPaint
                    )
                }
            }
        }
    }

    /**
     * 计算绘制文字时的基线到中轴线的距离
     *
     * @param p
     * @return 基线和centerY的距离
     */
    private fun getBaseline(p: Paint): Float {
        val fontMetrics = p.fontMetrics
        return (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent
    }

    private fun getTextBaselineY(p: Paint, targetY: Int, height: Int): Float {
        val distance = getBaseline(p)
        val centerY = targetY - height / 2
        return centerY + distance
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val adapter = parent.adapter
        val position = parent.getChildLayoutPosition(view)
        if (adapter is GroupSwordDelegate) {
            if (adapter.isGroupHeader(position)) {
                // 如果是头部，就在上方预留出 Header 的高度
                outRect.set(0, groupHeaderHeight, 0, 0)
            } else {
                // 如果不是头部，则在上方留出 1px画分隔线
                outRect.set(0, dividerHeightInPx, 0, 0)
            }
        }
    }
}